package com.xuexiang.xui_lib.component.button.shadowbutton;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

import com.xuexiang.xui_lib.ResourceTable;
import com.xuexiang.xui_lib.util.AttrValue;

/**
 * 可设置阴影效果的Button
 *
 * @author xuexiang
 * @since 2019/1/14 下午10:12
 */
public class ShadowButton extends BaseShadowButton implements Component.DrawTask, Component.TouchEventListener {
    private int COVER_ALPHA = 48;
    private Paint mPressedPaint;
    private Color mPressedColor;

    public ShadowButton(Context context) {
        super(context);
    }

    public ShadowButton(Context context, AttrSet attrSet) {
        super(context, attrSet, "");
    }

    public ShadowButton(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    @Override
    protected void init(Context context, AttrSet attrSet) {
        super.init(context, attrSet);
        COVER_ALPHA = AttrValue.get(attrSet, "sb_alpha_pressed", COVER_ALPHA);
        mPressedColor = AttrValue.get(attrSet, "sb_color_pressed",
            new Color(context.getColor(ResourceTable.Color_default_shadow_button_color_pressed)));

        mPressedPaint = new Paint();
        mPressedPaint.setStyle(Paint.Style.FILL_STYLE);
        mPressedPaint.setColor(mPressedColor);
        mPressedPaint.setAlpha(0);
        mPressedPaint.setAntiAlias(true);
        addDrawTask(this, DrawTask.BETWEEN_BACKGROUND_AND_CONTENT);
        setTouchEventListener(this);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        super.onDraw(component, canvas);
        if (mShapeType == 0) {
            canvas.drawCircle(mWidth / 2F, mHeight / 2F, mWidth / 2.1038f,
                mPressedPaint);
        } else {
            canvas.drawRoundRect(mRectF, mRadius, mRadius, mPressedPaint);
        }
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                mPressedPaint.setAlpha(COVER_ALPHA / 255f);
                invalidate();
                break;
            case TouchEvent.CANCEL:
            case TouchEvent.PRIMARY_POINT_UP:
                mPressedPaint.setAlpha(0);
                invalidate();
                break;
            default:
                break;
        }
        return true;
    }

    public Color getPressedColor() {
        return mPressedColor;
    }

    /**
     * Set the pressed color.
     *
     * @param pressedColor pressed color
     */
    public void setPressedColor(Color pressedColor) {
        mPressedPaint.setColor(pressedColor);
        invalidate();
    }
}
